package org.jetlinks.pro.assets;

import org.jetlinks.pro.assets.aop.AopAssetsControllerHandler;
import org.jetlinks.pro.assets.aop.AopAssetsControllerSupport;
import org.jetlinks.pro.assets.impl.DefaultAssetManager;
import org.jetlinks.pro.assets.impl.DimensionAssetsProperties;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.*;
import org.springframework.transaction.reactive.TransactionalOperator;

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(DimensionAssetsProperties.class)
public class AssetsConfiguration {

    @Bean
    @Primary
    public CompositeAssetBindManager assetBindManager(ObjectProvider<AssetBindManager> managers,
                                                      ApplicationEventPublisher eventPublisher) {
        CompositeAssetBindManager manager = new CompositeAssetBindManager(eventPublisher);
        managers.forEach(manager::addManager);
        return manager;
    }

    @Bean
    @ConditionalOnProperty(prefix = "jetlinks.assets-controller", name = "enabled", havingValue = "true", matchIfMissing = true)
    public AopAssetsControllerSupport aopTenantAccessHandler(@Lazy AssetBindManager assetBindManager,
                                                             @Lazy TransactionalOperator transactionalOperator) {
        AopAssetsControllerSupport support = new AopAssetsControllerSupport();
        support.setAdvice(new AopAssetsControllerHandler(transactionalOperator, assetBindManager));
        return support;
    }

    @Bean
    public DefaultAssetManager defaultAssetManager(ObjectProvider<AssetSupplier> assetSuppliers){
        return new DefaultAssetManager(assetSuppliers);
    }

    @Bean
    public ApplicationContextAware assetsHolderProviderRegister(ObjectProvider<AssetsHolderProvider> providers) {
        providers.forEach(AssetsHolderHolder::addProvider);
        return ctx -> {

        };
    }


}
